import IO from 'socket.io';
import md5 from 'md5';

export default class Clients{

  io = null;
  md5salt = "Wednesday";

  clients = {
  }

  clientEvents = {
  }

  genToken(uid){
    return md5(md5(uid + this.md5salt)).substring(1, 9);
  }

  createToken(uid){
    var token = this.genToken(uid);
    this.clients[token] = {
      userid:uid,
      data:{},
      events:[],
      socket:null
    }
    return token;
  }

  on(event, checkdata, fn){

    this.clientEvents[event] = async data=>{
      if (this.clients[data.token]){
        var client = this.clients[data.token];
        await fn(data);
        client.socket.emit(event+"_return", {
          emitId: data.emitId?data.emitId:0,
          ok:1
        });
      }
    }
  }

  reply(token, event, data){
    if (this.clients[token]){
      this.clients[token].socket.emit(event + "_reply", data);
    }
  }

  emit(token, event, data){
    if (this.clients[token]){
      this.clients[token].socket.emit(event, data);
    }
  }

  usercount(){
    var a = 0;
    Object.keys(this.clients).map(v=>{
      a++;
    });
    return a;
  }

  constructor(server){
    this.io = new IO(server);

    this.io.on('connection', socket=>{

      socket.on("user_login", data=>{
        console.log('TOKEN: ' + data.token + " LOGINED.   NOW ONLINE USERS: " + this.usercount());

        if (this.clients[data.token]){
          Object.keys(this.clientEvents).map(e=>{
            socket.on(e, this.clientEvents[e]);
          });
          this.clients[data.token].socket = socket;

          socket.on('disconnect', ()=>{
            console.log('TOKEN: ' + data.token + " DISCONNECTED.");
            socket = null;
            this.clients[data.token] = null;
          });

          socket.emit('user_login_return', data=>{
            ok:1
          });
        }else{
          // 服务端主动切断连接？
        }
      });
    });
  }
}
